const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu("自定义组件/ChangeImgUtil")
export default class ChangeImgUtil extends cc.Component {
    @property([cc.SpriteFrame])
    sfs: cc.SpriteFrame[] = [];
    @property({ displayName: "是否循环" })
    loop: boolean = false;
    private spriteComponent: cc.Sprite = null
    get sprite() {
        if (this.spriteComponent == null) this.sprite = this.node.getComponent(cc.Sprite);
        return this.spriteComponent
    }
    set sprite(sp: cc.Sprite) {
        this.spriteComponent = sp
    }
    nowIdx: number = 0;
    tiem: number = 0;
    tiem2: number = 0;
    time: number = 0;
    changeImgById(idx: number) {
        if (!this.sprite) {
            this.sprite = this.node.getComponent(cc.Sprite);
        }
        if (!this.sprite) {
            cc.warn("current node can not find cc.Sprite!");
        } else {
            if (this.sfs[idx] == null) {
                console.warn("没有对应的图片，图片id:", idx)
            }
            this.sprite.spriteFrame = this.sfs[idx];
            this.nowIdx = idx;
        }
    }

    next() {
        this.nowIdx++;
        if (this.nowIdx > this.sfs.length-1) {
            if (this.loop) {
                this.nowIdx = 0;
            } else {
                cc.warn("it's last one")
            }
        } else {
        }
        this.changeImgById(this.nowIdx);
    }

    last() {
        this.nowIdx--;
        if (this.nowIdx < 0) {
            if (this.loop) {
                this.nowIdx = this.sfs.length - 1;
            } else {
                cc.warn("it's first one")
            }
        } else {
        }
        this.changeImgById(this.nowIdx);
    }
    /**
     * 播放
     * @param sum 单位帧 
     * @param time 暂停时间
     * */
    onPlay(sum: number, time: number) {
        this.onStop();
        this.tiem = 0;
        this.tiem2 = sum
        this.time = time;
        this.schedule(this.onTime, sum * 0.033)
    }
    onTime() {
        this.tiem = this.tiem + this.tiem2 * 0.033
        if (this.nowIdx >= this.sfs.length) {
            this.nowIdx = 0;
        }
        if (this.tiem >= this.time) {
            this.tiem = 0;
            this.nowIdx = 0;
            this.next();
        } else {
            this.next();
        }
    }
    /**暂停播放 */
    onStop() {
        this.unschedule(this.onTime);
    }
}
